package net.comm.common;

import   sun.net.ftp.*; 
import   java.io.*; 
import   java.io.IOException; 
import   sun.net.TelnetOutputStream; 
/** 
  *   一个连接FTP的类 
  *   只有上传文件 
  *   通过测试 
  * 
  * 
  *   @author     jiaoyan 
  *   @version   1.0 
  */ 
public   class   Ftpupload   { 
    FtpClient   client; 
    private   String   host= "123.456.789.123 ";//FTP服务器IP 
    private   String   username= "anonymous ";	//FTP用户名字 
    private   String   password= " ";			//FTP密码 
    private   String   path   =   "/wanglei ";  //目录 
    private   int   port   =   21;              //FTP端口 
    /** 
      *   连接服务器方法 
      */ 
    public   void   connect()   { 
        try   { 
            client   =   new   FtpClient(host); 
            client.login(username,   password); 
            //设置成2进制传输 
            client.binary(); 
            client.cd(path); 
            System.out.println( "登陆成功 "); 
        } 
        catch   (FtpLoginException   e)   { 
            System.out.println( "无权限相连接 "   +   e.getMessage()); 
        } 
        catch(IOException   e){ 
            System.out.println( "连接失败 "+e.getMessage()); 
        } 
        catch(SecurityException   e){ 
            System.out.println( "用户名字或者密码不对 "); 
        } 

    } 
    /** 
      *   上传文件 
      *   @param   fileName   String   文件名字 
      *   @param   filePath   String   文件路径 
      *   @return   boolean 
      */ 
    public   boolean   upLoad(String   fileName,String   filePath)   { 
        File   localFile   =   new   File(filePath); 

        try   { 
            TelnetOutputStream   os   =   client.put(fileName); 
            java.io.File   file_in   =   new   java.io.File(filePath); 
            FileInputStream   is   =   new   FileInputStream(file_in); 
            byte[]   bytes   =   new   byte[1024]; 
            int   c; 
            while   (   (c   =   is.read(bytes))   !=   -1)   { 
                os.write(bytes,   0,   c); 
            } 
            is.close(); 
            os.close(); 
            System.out.println( "传送成功 "); 

        } 
        catch   (Exception   e)   { 
            System.out.println( "上传文件出错 "+e.getMessage()); 
            return   false; 
        } 
        return   true; 
    } 
    public   void   closeServer()throws   Exception{ 
        if(client!=null){ 
            client.closeServer(); 
            System.out.println( "FTP已经关闭 "); 
        } 
    } 
} 

